package svc

import (
	"go-zero-service/service/user/api/internal/config"
	"log"
	"os"
	"time"

	"github.com/go-redis/redis"
	elastic "github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type ServiceContext struct {
	Config    		config.Config
	UserModel 		*gorm.DB
	DefaultRedis 	*redis.Client
	OrderRedis 		*redis.Client
	Elastic         *elastic.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	UserModel := NewDbGrom(c.Mysql.User)
	DefaultRedis := NewRedis(c.Redis.Default)
	OrderRedis := NewRedis(c.Redis.Order)
	Elastic := NewElastic(c.Elastic)

	return &ServiceContext{
		Config:    		c,
		UserModel: 		UserModel,
		DefaultRedis: 	DefaultRedis,
		OrderRedis: 	OrderRedis,
		Elastic:        Elastic,
	}
}

func NewDbGrom(dbLink string) *gorm.DB {
	//启动Gorm支持
	g, err := gorm.Open(mysql.Open(dbLink), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "",   // 表名前缀，`User` 的表名应该是 `t_users`
			SingularTable: true, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `t_user`
		},
	})
	//如果出错就GameOver了
	if err != nil {
		panic(err)
	}

	return g
}

func NewRedis(r *config.RedisConfig) *redis.Client {
	rdb := redis.NewClient(&redis.Options{
		Addr:     		r.Addr,
		Password: 		r.Pass,
		DB:       		r.Db,
	})

	_, err := rdb.Ping().Result()
 
	if err != nil {
		panic(err)
	}

	return rdb
}

func NewElastic(e *config.ElasticConfig) *elastic.Client{
	errorlog := log.New(os.Stdout, "ELASTIC_LOG", log.LstdFlags)

	client, err := elastic.NewClient(
        elastic.SetURL(e.Addr),
		elastic.SetErrorLog(errorlog),
        elastic.SetSniff(e.Sniff),
        elastic.SetHealthcheckInterval(time.Duration(e.HealthcheckInterval)*time.Second), // 设置监控检查时间间隔
        elastic.SetMaxRetries(e.MaxRetries))   // 设置请求失败最大重试次数

    if err != nil {
        // Handle error
		panic(err)
    }

	return client
}
